import axios from 'axios'
export default {
    namespaced:true,
    state: {
        shopList:[]
    },
    getters: {
        //计算选中的商品总数
        total(state) {
          return  state.shopList.reduce((prev, item) => { 
                if (item.checked) return prev + 1
                return prev
            },0)
         },
        num(state) {
        return state.shopList.reduce((prev, item) => { 
                if (item.checked) return prev + (item.price * item.num)
                return prev
            },0).toFixed(2)
         }
    },
    mutations: {
        setShopList(state, payload) {
            state.shopList = payload
        },
        updateCount(state, payload) {
            const obj = state.shopList.find(item => item.name === payload.id)
            obj.num = payload.count
        },
        del(state, payload) {
          state.shopList = state.shopList.filter(item => item.name !== payload.name)  
        },
        editChecked(state, payload) { 
            const obj = state.shopList.find(item => item.name === payload.name)
            obj.checked = !obj.checked
        },
        updateAll(state, payload) {
            state.shopList.forEach(item => item.checked = payload)
         }
    },
    actions: {
        async getGoodsList(context) { 
            try {
                const res = await axios({
                    url: 'http://localhost:3000/goodList',
                    method:'get'
                })
                context.commit('setShopList',res.data)
            } catch (error) {
                console.log(error);
            }
        }
    }
}